package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"log"
)

type User struct {
	Name   string `json:"user"`
	Native bool   `json:"native,omitempty"`
	Age    int
	HB     []string `json:"hobby"`
}

type MinimalUser struct {
	Name string `json:"user"`
	Age  int
}

func main() {
	u1 := []User{
		{Name: "zhou", Native: true, Age: 32, HB: []string{"surfing", "movie", "fishing"}},
		{Name: "wang", Native: false, Age: 23, HB: []string{"photoing", "swiming", "writing"}},
	}

	var jdata []byte
	jdata, err := json.MarshalIndent(u1, "", "    ")
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("------------\nGo struct -> JSON:\n%s\n", jdata)

	var u2 []MinimalUser
	if err := json.Unmarshal(jdata, &u2); err != nil {
		log.Fatal(err)
	}
	fmt.Printf("\n------------------------------------\nJSON -> Go struct ( from []byte ) :\n %#v\n", u2)

	var u3 []MinimalUser
	// bytes.NewReader也可以
	if err = json.NewDecoder(bytes.NewBuffer(jdata)).Decode(&u3); err != nil {
		log.Fatal(err)
	}

	fmt.Printf("\n-----------------------------------------------------------\nJSON -> Go struct(from stream, by json.Decoder.Decode()) :\n %#v\n", u2)
}
